import { UserOutlined, BarChartOutlined,LineChartOutlined,FileSearchOutlined,FileProtectOutlined } from '@ant-design/icons';
import React from "react";
import getMenu from "@/routes/routerConfig";
import store from "@/redux/store";

import AccountManagement from "@/pages/accountManagement";
import RankingList from "@/pages/rankingList";
import CodeUpload from "@/pages/codeUpload";
import Explain from "@/pages/explain";
import Rules from '@/pages/rules';

// 基础菜单
let routes = [
    {
        label: "任务规则",
        key: "/rules",
        element: Rules,
        icon: <FileSearchOutlined />,
        disabled: false,
    },
    {
        label: "数据说明",
        key: "/explain",
        element: Explain,
        icon: <LineChartOutlined />,
        disabled: false,
    },
    {
        label: "代码提交",
        key: "/codeUpload",
        element: CodeUpload,
        icon: <FileProtectOutlined />,
        disabled: false,
    },
    {
        label: "排行榜",
        key: "/rankingList",
        element: RankingList,
        icon: <BarChartOutlined />,
        disabled: false,
    },
    {
        label: "账户管理",
        key: "/accountManagement",
        element: AccountManagement,
        icon: <UserOutlined />,
        disabled: false,
    },
];

// 登录后刷新页面
store.subscribe(() => {
    const { reload } = store.getState();
    if (reload) location.reload();
});

// 把接口获取的菜单重写
function setmenu(list) {
    for (let i = 0; i < list.length; i++) {
        let item = list[i];
        item.label = item.meta.title;
        item.key = item.path;
        item.icon = item.meta.icon;
        delete item.meta.title;
        delete item.path;
        delete item.meta.icon;

        // 直接使用静态引入的组件
        item.element = getComponent(item.component);

        if (item.children) setmenu(item.children);
    }
    return list;
}

// 获取组件的函数
function getComponent(componentName) {
    switch (componentName) {
        case 'AccountManagement':
            return AccountManagement;
        case 'RankingList':
            return RankingList;
        case 'CodeUpload':
            return CodeUpload;
        case 'Explain':
            return Explain;
        case 'Rules':
            return Rules;
        default:
            return () => import(`../components/error302`); // 默认重定向
    }
}

function iconBC(name) { return React.createElement(Icon[name]); }

const token = JSON.parse(localStorage.getItem(window.envConfig['ROOT_APP_INFO']))?.token;
const menu = JSON.parse(localStorage.getItem(window.envConfig['ROOT_APP_INFO']))?.menuList;

if (token) getMenu();

// 从接口请求菜单
if (token && menu) {
    routes = setmenu(menu);
    
    function setIcon(res) {
        for (let i = 0; i < res.length; i++) {
            const element = res[i];
            let IconItem = element.icon;
            if (IconItem) element.icon = iconBC(IconItem);
            if (element.children) setIcon(element.children);
        }
    }
    setIcon(routes);
}

export default routes;